package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.R;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.SysUserDto1;
import com.itheima.ydd.entity.SysRole;
import com.itheima.ydd.entity.SysUser;
import com.itheima.ydd.service.ISysRoleService;
import com.itheima.ydd.service.ISysUserService;
import com.itheima.ydd.service.IYddSysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/sys_user")
public class YddSysUserController {
    @Autowired
    private IYddSysUserService iYddSysUserService;
    @Autowired
    private ISysRoleService iSysRoleService;
    @Autowired
    private ISysUserService iSysUserService;

    /**
     * md5加密
     *
     * @param password 密码
     */
    private String generatePassword(String password) {
        return DigestUtils.md5DigestAsHex(password.getBytes());
    }

    @GetMapping("/list")
    public ResultData list(String login_name, String status, String phone, int page, int limit) {
        //分页构造器
        Page<SysUser> pageInfo = new Page<>();
        //条件过滤器
        LambdaQueryWrapper<SysUser> sysUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysUserLambdaQueryWrapper.eq(StringUtils.isNotEmpty(login_name), SysUser::getLoginName, login_name);
        if (StringUtils.isNotEmpty(status)) {
            sysUserLambdaQueryWrapper.eq(SysUser::getStatus, Integer.parseInt(status));
        }

        sysUserLambdaQueryWrapper.eq(StringUtils.isNotEmpty(phone), SysUser::getPhone, phone);
        //查询
        List<SysUser> list = iSysUserService.list(sysUserLambdaQueryWrapper);
        List<SysUserDto1> sysUserDtoList = new ArrayList<>();
        for (SysUser sysUser : list) {
            SysUserDto1 sysUserDto = new SysUserDto1();
            BeanUtils.copyProperties(sysUser, sysUserDto);
            String roleId = sysUser.getRoleId();
            String[] split = roleId.split(",");
            List<String> roleIds = new ArrayList<>();
            List<String> rolenames = new ArrayList<>();
            for (String s : split) {
                String replace = s.replace("[", "").replace("]", "").replace("\"", "").trim();
                SysRole byId = iSysRoleService.getById(replace);
                String name = byId.getName();
                rolenames.add(name);
                roleIds.add(replace);
            }

            sysUserDto.setRole_id(roleIds);
            sysUserDto.setRolename(rolenames);

            sysUserDtoList.add(sysUserDto);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("data", sysUserDtoList);
        map.put("totalPages", pageInfo.getPages());
        map.put("currentPage", pageInfo.getCurrent());
        map.put("pageSize", pageInfo.getSize());
        map.put("count", pageInfo.getTotal());
        return ResultData.ok("成功", map);
    }

    @GetMapping("/rowInfo")
    public ResultData rowInfo(String id) {
        SysUser sysUser = iYddSysUserService.getById(id);
        String roleId = sysUser.getRoleId();
        String[] split = roleId.split(",");
        List<String> roleIds = new ArrayList<>();
        for (String s : split) {
            String replace = s.replace("[", "").replace("]", "").replace("\"", "").trim();
            roleIds.add(replace);
        }
        sysUser.setRole_id(roleIds);
        log.info(roleIds.toString());
        return ResultData.ok("", sysUser);
    }

    //添加功能
    @PostMapping("add")
    public ResultData add(@RequestBody HashMap<String, Object> map) {
        //封装对象
        SysUser user = new SysUser();
        String login_name = (String) map.get("login_name");
        user.setLoginName(login_name);

        String password = (String) map.get("password");
        password = generatePassword(password);
        user.setPassword(password);

        String phone = (String) map.get("phone");
        user.setPhone(phone);

        String name = (String) map.get("name");
        user.setName(name);

        String email = (String) map.get("email");
        user.setEmail(email);

        Integer status = (Integer) map.get("status");
        user.setStatus(status);

        ArrayList<String> role_id = (ArrayList<String>) map.get("role_id");
        ArrayList<String> roleids = new ArrayList<>();

        for (String s : role_id) {
            String s1 = "\"" + s + "\"";
            roleids.add(s1);
        }
        String string = roleids.toString();
        user.setRoleId(string);

        iYddSysUserService.save(user);
        return ResultData.ok("添加成功", "添加成功");
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @GetMapping("/del")
    public R deleteById(String id) {
        iYddSysUserService.removeById(id);
        return R.success("Code", 200);
    }

    /**
     * 修改
     *
     * @param sysUser
     * @return
     */
    @PostMapping("/update")
    public R update(@RequestBody SysUser sysUser) {
        if (sysUser.getRole_id() != null) {
            List<String> role_id = sysUser.getRole_id();
            String s1 = role_id.toString();
            String substring = s1.substring(1, s1.length() - 1);
            String[] split = substring.split(",");
            List<String> roleids = new ArrayList<>();
            for (String s : split) {
                s1 = "\"" + s + "\"";
                roleids.add(s1);
            }
            sysUser.setRoleId(roleids.toString());
        }

        iYddSysUserService.updateById(sysUser);
        return R.success("code", 200);
    }


}
